<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item  label="用户名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="部门状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >创建用户</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-sort"-->
<!--          size="mini"-->
<!--          @click="toggleExpandAll"-->
<!--        >展开/折叠</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="accountList"
      row-key="id"
    >
      <el-table-column type="selection" width="80" align="center" />
      <el-table-column prop="userId" label="主键" v-if="false" ></el-table-column>
      <el-table-column prop="username" label="登录账号" ></el-table-column>
<!--      <el-table-column prop="userId" label="用户id"></el-table-column>-->
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="loginDate" label="登录时间" ></el-table-column>
      <el-table-column prop="loginIp" label="登录ip" >
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="updateData(scope.row)"
          >修改密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" :before-close="handleClose" append-to-body>
      <el-form ref="form" v-loading="loadingForm" :model="form" :rules="rules" style="margin-top: 30px;margin-left: 20px" label-width="80px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="账号" prop="username">
              <el-input v-model="form.username"  :disabled="form.userId" placeholder="请输入登录账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="form.password" placeholder="请输入密码" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input  type="password" v-model="form.confirmPassword" placeholder="请输入确认密码" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row>-->
<!--          <el-col :span="12">-->
<!--        <el-form-item label="账号状态">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in dict.type.sys_normal_disable"-->
<!--              :key="dict.value"-->
<!--              :label="dict.value"-->
<!--            >{{dict.label}}</el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLowerUser, createLowerUser,updateLowerUserData,delUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {Message} from "element-ui";

export default {
  name: "Dept",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.form.password !== value) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      loadingForm:false,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      accountList: [],
      // 部门树选项
      deptOptions: [],
      isUpdate: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "账号不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        confirmPassword:[
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          { required: true, validator: equalToPassword, trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {


    /** 获取下级用户数据 */
    getList() {
      this.loading = true;
      getLowerUser({}).then(response => {
        this.accountList = response.data
      }).finally(()=>{
        this.loading = false;
      })
    },


    /**
     * 修改子账号的密码
     */
    updateData(row){
      console.log(row)
      this.loadingForm = true;
      getLowerUser(row).then((res)=>{
        this.form = res.data[0]
      }).finally(()=>{
        this.loadingForm = false;
      })
      this.title = "修改账号密码";
      this.open = true;
    },


    /**
     * 关闭model
     */
    handleClose(){
      this.reset();
      this.open = false;
    },


    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id:undefined,
        username: undefined,
        password: undefined,
        confirmPassword: undefined,
        createTime: undefined,
        loginDate: undefined,
        loginIp: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加子账号";
      // listDept().then(response => {
      //   this.deptOptions = this.handleTree(response.data, "deptId");
      // });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.userId){
            //修改用户数据
            updateLowerUserData(this.form).then((res)=>{
              if(res.code === 200){
                Message.success("密码修改成功！")
              }
            }).finally(()=>{
              this.open = false;
            })
          }else{
            //创建新的子账号数据
            createLowerUser(this.form).then((res)=>{
              console.log(res)
              if(res.code === 200){
                Message.success("子账户创建成功！")
                this.getList()
              }
            }).finally(()=>{
              this.open = false;
            })
          }

          //添加子账号的逻辑
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除账号"' + row.username + '？删除后将取消关联的媒体账号。"').then(() => {
        this.loading = true;
        row.delFlag = "2"
        delUser(row.userId);  //逻辑删除用户数据
        return updateLowerUserData(row);  //再删除部门数据
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    //
    //
    //   this.$modal.confirm('是否确认删除账号"' + row.username + '？删除后将取消关联的媒体账号。"').then(function() {
    //     //修改用户数据
    //     this.form.delFlag = "2"
    //     return  updateLowerUserData(this.form);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {});
    }
  }
};
</script>
